<?

include_once ("Server.php");
include_once ("config.php");

class TeamRepo extends BaseRepo{

	protected function getEntityName(){
		return "Team";
	}

	public function getPickingTeam($draft)
	{
		$query = "WHERE ID = (SELECT CASE WHEN po.toTeamID is not null THEN po.toTeamID "; 
		$query = $query."                 ELSE t.id ";
		$query = $query."            END ";
		$query = $query."     FROM Team t ";
		$query = $query."     LEFT JOIN PickOverride po on t.id = po.fromTeamID ";
		$query = $query."     WHERE t.draftOrder = ".$draft->currentDraftOrder()." AND t.draftID = ".$draft->id.")";
		
		$teams = $this->get($query);
		
		
		return $teams[0];
	}

	public function getAllOrphanTeams()
	{
		$draftRepo = new DraftRepo();
		$drafts = $draftRepo->getActiveDrafts();
		$query = $query . "WHERE x.userID is null AND x.draftID in (";
		$numCount = count($drafts);
		$i = 0;
		$retArray = array();
		foreach ($drafts as $d){
			$draftArray = array(
				"draft" => $d);
			$retArray[$d->id] = $draftArray;
			$query = $query.$d->id;
			if (++$i == $numCount){
				$query = $query.")";
			} else {
				$query = $query.",";
			}
		}
		$teams = $this->get($query);
		foreach ($teams as $team){
			$draftID = $team->draftID;
			$retArray[$draftID]["teamList"][] = $team;
		}
		return $retArray;
	}

	function getAllTeamsInDraft($draftID)
	{
		$con = connect();
		$query = "SELECT id,name,user_id,draft_id,draft_order FROM team ";
		$query = $query . "WHERE draft_id =".$draftID." ORDER BY draft_order ASC";
		$teamRows = query($query, $con);
		if (mysql_num_rows($teamRows) > 0)
		{
			$retVal = array();
			while($teamRow =  mysql_fetch_array($teamRows))
			{
				$team = new Team($teamRow['id'],
								 $teamRow['name'],
								 $teamRow['user_id'],
								 $teamRow['draft_id'],
								 $teamRow['draft_order']);
				$retVal[] = $team;
			}
		}
		disconnect($con);
		return $retVal;
	}

	function getAllTeamsForUser($userID)
	{
		$con = connect();
		$query = "SELECT id,name,user_id,draft_id,draft_order FROM team ";
		$query = $query . "WHERE user_id=".$userID;
		$teamRows = query($query, $con);
		if (mysql_num_rows($teamRows) > 0)
		{
			$teams = array();
			while($teamRow =  mysql_fetch_array($teamRows))
			{
				$t = new Team($teamRow['id'],
							 $teamRow['name'],
							 $teamRow['user_id'],
							 $teamRow['draft_id'],
							 $teamRow['draft_order']);
				$teams[] = $t;
			}
		}
		disconnect($con);
		return $teams;
	}

	public function addUserToTeam($teamID, $userID)
	{
		$con = connect();
		$q = "UPDATE Team SET userID=".$userID." ";
		$q = $q."WHERE id=".$teamID;
		print $q;
		query($q, $con);
		disconnect($con);
		return $team;
	}
}

?>